package com.sooth.micro.camunda.config;

import com.sooth.common.core.utils.SpringUtils;
import com.sooth.micro.camunda.converter.bean.extension.ExtBpmConstant;
import com.sooth.micro.camunda.converter.bean.extension.ProcessStatus;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.ExecutionListener;
import org.camunda.bpm.model.bpmn.instance.EndEvent;
import org.camunda.bpm.model.bpmn.instance.FlowElement;
import org.camunda.bpm.model.bpmn.instance.StartEvent;


@Slf4j
public class CamundaGlobalListener implements ExecutionListener {
    @Override
    public void notify(DelegateExecution execution) throws Exception {
        FlowElement bpmnModelElementInstance = execution.getBpmnModelElementInstance();
        String processInstanceId = execution.getProcessInstanceId();
        RuntimeService runtimeService = SpringUtils.getBean(RuntimeService.class);
        if (bpmnModelElementInstance instanceof StartEvent) {
            runtimeService.setVariable(processInstanceId, ExtBpmConstant.PROCESS_STATUS, ProcessStatus.RUNNING.name());
        } else if (bpmnModelElementInstance instanceof EndEvent) {
            String processStatus = (String) runtimeService.getVariable(processInstanceId, ExtBpmConstant.PROCESS_STATUS);
            if (ProcessStatus.RUNNING.name().equals(processStatus)) {
                runtimeService.setVariable(processInstanceId, ExtBpmConstant.PROCESS_STATUS, ProcessStatus.COMPLETED.name());
            }
        }
    }

}
